package com.film.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.film.domain.Film;
import com.film.domain.FilmShowings;
import com.film.domain.ReviewAndFilm;
import com.film.domain.UserOrder;
import com.film.service.FilmService;
import com.film.service.ReviewService;
import com.film.service.ShowingsService;
import com.film.service.impl.FilmServiceImpl;
import com.film.service.impl.ReviewServiceImpl;
import com.film.service.impl.ShowingsServiceImpl;

@WebServlet("/showings")
public class ShowingsController extends  HttpServlet{
	
	private ShowingsService showingsService = new ShowingsServiceImpl();
	private FilmService filmService = new FilmServiceImpl();
	private ReviewService reviewService = new ReviewServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String filmId = request.getParameter("filmId");
		List<String> showingsDateList = showingsService.selectShowingsDateByFilm(Integer.parseInt(filmId), 0);
		if(showingsDateList.size() == 0) {
			Date date = new Date();
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String str = format.format(date);
			showingsDateList.add(str);
		}
		List<FilmShowings>  showingsList = showingsService.selectShowingsByDate(showingsDateList.get(0), Integer.parseInt(filmId), 0);
		//按放映时间排序
		if(showingsList != null && showingsList.size() != 0) {
			showingsList.sort(new Comparator<FilmShowings>() {
				@Override
				public int compare(FilmShowings o1, FilmShowings o2) {
					return o1.getShowingsStartTime().compareTo(o2.getShowingsStartTime());
				}
			});
		}
		Film filmDetails = filmService.FilmOneTypeAndDirectoe(Integer.parseInt(filmId));
		HttpSession session = request.getSession();
		ReviewAndFilm reviewAndFilm = reviewService.selectFilmReviewScore(Integer.parseInt(filmId));
		session.setAttribute("showingsDateList", showingsDateList);
		session.setAttribute("filmDetails", filmDetails);
		session.setAttribute("showingsList", showingsList);
		session.setAttribute("reviewAndFilm1", reviewAndFilm);
		response.sendRedirect("showings.jsp?flag=0");
	}
}
